#include <stdlib.h>
#include <stdio.h>
#include <p89lpc9351.h>
#include "lcd.h"

#define XTAL 7373000L
#define BAUD 115200L

void Wait1S (void)
{
	_asm
	mov R2, #40
L3: mov R1, #250
L2: mov R0, #184
L1: djnz R0, L1 ; 2 machine cycles-> 2*0.27126us*184=100us
    djnz R1, L2 ; 100us*250=0.025s
    djnz R2, L3 ; 0.025s*40=1s
    _endasm;
}

void InitADC(void)
{
	// Set adc1 channel pins as input only 
	P0M1 |= (P0M1_4 | P0M1_3 | P0M1_2 | P0M1_1);
	P0M2 &= ~(P0M1_4 | P0M1_3 | P0M1_2 | P0M1_1);

	BURST1=1; //Autoscan continuos conversion mode
	ADMODB = CLK0; //ADC1 clock is 7.3728MHz/2
	ADINS  = (ADI13|ADI12|ADI11|ADI10); // Select the four channels for conversion
	ADCON1 = (ENADC1|ADCS10); //Enable the converter and start immediately
	while((ADCI1&ADCON1)==0); //Wait for first conversion to complete
}

void main (void)
{
	char val[20];
	
	InitADC();
	InitLCD();
	
	TMOD = 0;
	TMOD &= ~T0M0;
	TMOD |= T0M1;
	TAMOD &= !T0M2;
	
	TH0 = 255;
	
	TCON &= ~TR0;
	TCON |= TR0;
	
	while(1)
	{
		//RTCCON |= RTCEN;
		
		lcdCommand(LCD_CLEAR);
		lcdCommand(LCD_HOME);
		
		writeString("ADC values:");
		setLcdCursor(1,0);

		sprintf(val, "%i %i", TL0, TH0);
		writeString(val);
	}
}
